package com.example.demo.course.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.demo.course.Course;
import com.example.demo.course.dto.CourseExcelDTO;
import com.example.demo.course.listener.CourseExcelListener;
import com.example.demo.course.repository.CourseRepository;
import com.example.demo.course.repository.UserCourseRepository;
import com.example.demo.course.service.CourseService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

@Service

public class CourseServiceImpl implements CourseService {

    private final CourseRepository courseRepository;
    private final UserCourseRepository userCourseRepository;

    // 手动录入课程
    @Override
    public Course saveCourse(Course course) {
        return courseRepository.save(course);
    }

    // 批量保存课程
    @Override
    @Transactional
    public List<Course> saveBatchCourses(List<Course> courses) {
        return courseRepository.saveAll(courses);
    }

    @Override
    public void importExcel(MultipartFile file, Long userId) {
        try {
            EasyExcel.read(
                    file.getInputStream(),
                    CourseExcelDTO.class,
                    new CourseExcelListener(this, userId, userCourseRepository)
            ).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException("Excel导入失败：" + e.getMessage());
        }
    }

    // 获取所有课程
    @Override
    public List<Course> getAllCourses() {
        return courseRepository.findAll();
    }

    @Override
    public Optional<Course> getCourseById(Long id) {
        return courseRepository.findById(id);
    }

    // 根据用户ID获取课程
    @Override
    public List<Course> getCoursesByUserId(Long userId) {
        List<Long> courseIds = userCourseRepository.findCourseIdsByUserId(userId);
        return courseRepository.findAllById(courseIds);
    }
    public CourseServiceImpl(CourseRepository courseRepository, UserCourseRepository userCourseRepository) {
        this.courseRepository = courseRepository;
        this.userCourseRepository = userCourseRepository;
    }

}